<?php

namespace Viettrans\BackBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormError;

/**
 * User controller.
 *
 * @Route("/bo/user")
 */
class UserController extends Controller
{
    /**
     * @Route("/login", name="bo_user_login")
     * @Template()
     */
    public function loginAction() {
		$form = $this->createFormBuilder('', array('csrf_protection' => false))
		             ->add('user', 'text')
					 ->add('password', 'password')
					 ->getForm();
		
		$request = $this->getRequest(); 
		
		if ($request->getMethod() == 'POST') {
			$form->bindRequest($request);
			
			$formData = $this->getRequest()->get('form');
			
			# Get the array from the text file and assign it to $admins
			$adminsRaw = $this->container->getParameter("admins");

            $adminsParsed = explode(",", $adminsRaw);
			
            $admins = array();
            
            foreach ($adminsParsed as $adminParsed){
                list($user, $pass, $role) = explode(':', $adminParsed);
                $admins[$user] = array('pass'=>$pass, 'role'=>$role);
            }
            
			# Check user
			if (!array_key_exists($formData['user'], $admins)) {
				$form->addError(new FormError('User does not exist'));
			
			# Check password
			} elseif($admins[$formData['user']]['pass'] != $formData['password']) {
				$form->addError(new FormError('Password does not match'));
			
			# Ok
			} else {
				$this->get('session')->set('user',$formData['user']);
				return $this->redirect($this->generateUrl('bo_index'));
			}
		}
		
        return array('form'=>$form->createView());
    }
	
    /**
     * @Route("/logout", name="bo_user_logout")
     * @Template()
     */
    public function logoutAction() {
		$session = $this->get('session');
		
		if ($session->has('user')) $session->remove('user');
		
		return $this->redirect($this->generateUrl('bo_index'));
    }
}
